package com.woniu.woniu_bx.filter;

import com.woniu.woniu_bx.exception.ValidCaptchaException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description TODO
 * @Author leonie
 * @Date 2022/8/23 10:11
 */
@Slf4j
public class JwtVarifyFilter extends AbstractAuthenticationProcessingFilter {
    public JwtVarifyFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        attemptAuthentication((HttpServletRequest) request, (HttpServletResponse) response);
        chain.doFilter(request,response);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        log.debug("JwtVarifyFilter");
        String token = request.getHeader("token");
        if (token!=null){
            JwtToken jwtToken = new JwtToken(token);
            return this.getAuthenticationManager().authenticate(jwtToken);
        }else {
            throw new ValidCaptchaException("token失效");
        }
    }
}
